/**
 * @param {object} options
 * @param {number} options.diffTime 需要倒计时的时间差，单位为 ms，例如 10 秒倒计时，需要传入 10 * 1000
 * @param {function} options.onEnd 倒计时结束后执行的回调函数
 * @param {boolean} options.isDouble 是否需要返回的日期的格式为两位数，即不足两位前面自动补 0，默认为 true，不填则默认补位
 * @returns {{ timeFormat: object, Start: function, Pause: function }} timeFormat: 返回格式化后的时间日时分秒 {days：xx, hours:xx, minutes:xx, seconds:xx}，通过结构赋值获取所需的日期字段 , Start: 倒计时开始 , Pause :暂停倒计时
 */
type UseCountDown = (options: {
  diffTime: number;
  onEnd?: Function;
  isDouble?: boolean;
}) => {
  timeFormat: ComputedRef<{
    days: string;
    hours: string;
    minutes: string;
    seconds: string;
  }>;
  Start: () => void;
  Pause: () => void;
};

const useCountDown: UseCountDown = ({ diffTime, onEnd, isDouble = true }) => {
  if (typeof onEnd !== "function") {
    throw Error("onEnd should be a function");
  }

  if (typeof diffTime !== "number") {
    throw Error("diffTime should be a number");
  }

  const time = ref<number>(diffTime);
  let timer: NodeJS.Timeout | null = null;

  const numDeal = (num: number): string => {
    if (isDouble) {
      return num < 10 ? `0${num}` : `${num}`;
    }
    return `${num}`;
  };

  const timeFormat = computed(() => {
    const days = Math.floor(time.value / 1000 / 3600 / 24);
    const hours = Math.floor((time.value / 1000 / 3600) % 24);
    const minutes = Math.floor((time.value / 1000 / 60) % 60);
    const seconds = Math.floor((time.value / 1000) % 60);
    return {
      days: numDeal(days),
      hours: numDeal(hours),
      minutes: numDeal(minutes),
      seconds: numDeal(seconds),
    };
  });

  const CountTime = () => {
    timer = setInterval(() => {
      time.value -= 1000;
    }, 1000);
  };
  const Start = () => {
    if (timer) {
      clearInterval(timer);
    }
    CountTime();
  };
  const Pause = () => {
    if (timer) {
      clearInterval(timer);
      timer = null;
    }
  };


  const watchTime = () => {
    if (time.value <= 0) {
      onEnd?.();
      Pause();
    }
  };
  watch(time, watchTime);

  onUnmounted(() => {
    if (timer) {
      clearInterval(timer);
    }
  });

  return {
    timeFormat,
    Start,
    Pause,
  };
};

export default useCountDown;
